package com.example.shop.controller.backstage;

import com.alibaba.fastjson.JSON;
import com.example.shop.model.User;
import com.example.shop.service.UserService;
import com.example.shop.utils.PageBean;
import com.example.shop.utils.Result;
import com.example.shop.utils.TokenUtil;
import com.example.shop.utils.UserToken;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Controller
//@ResponseBody  这两个注解的作用相当于 @RestController 注解
@RestController
@RequestMapping("/backstage")
public class BackUserController {
    @Resource
    private UserService userService;

    @RequestMapping("/adminLogin")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        User login = userService.login(user);
        if (login != null && login.getRoleId() == 1) {
            String token = TokenUtil.createToken(user);
            UserToken userToken = new UserToken(login, token);
            map.put("message", "成功");
            map.put("user", userToken);
        } else {
            map.put("message", "管理员账号或密码错误");
        }
        return map;
    }

    @RequestMapping("/getUsers")
    public String getUsers(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "5") Integer pageSize, @RequestParam(defaultValue = "") String search) {
        PageBean<User> users = userService.getUsers(pageNo, pageSize, search);
        Result<PageBean<User>> res = new Result<>();
        res.setCode("0");
        res.setData(users);
        return JSON.toJSONString(res);
    }

    @DeleteMapping("/deleteUser/{id}")
    public Map<String, String> deleteUser(@PathVariable Integer id) {
        Map<String, String> map = new HashMap<>();
        int count = userService.deleteUser(id);
        if (count > 0) {
            map.put("message", "成功");
        } else {
            map.put("message", "删除失败");
        }
        return map;
    }

    @PutMapping("/insertUser")
    public Map<String, String> insertUser(@RequestBody User user) {
        Map<String, String> map = new HashMap<>();
        user.setCreated(new Date());
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        int count = userService.insertUser(user);
        if (count > 0) {
            map.put("message", "成功");
        } else {
            map.put("message", "增加失败");
        }
        return map;
    }

    @PostMapping("/updateUser")
    public Map<String, String> updateUser(@RequestBody User user) {
        Map<String, String> map = new HashMap<>();
        int count = userService.updateUser(user);
        if (count > 0) {
            map.put("message", "成功");
        } else {
            map.put("message", "修改失败");
        }
        return map;
    }
}
